package com.company.genealogy.web.service.impl;

import com.company.genealogy.web.entity.User;
import com.company.genealogy.web.mapper.UserMapper;
import com.company.genealogy.web.service.WxApiService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信API服务实现类
 * @author chenzhixiang
 */
@Service
public class WxApiServiceImpl implements WxApiService {
    
    @Value("${wx.appid}")
    private String appid;
    
    @Value("${wx.secret}")
    private String secret;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Override
    public Map<String, Object> getOpenidByCode(String code) {
        try {
            // 构建请求URL
            String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appid, secret, code
            );
            
            // 调用微信API，获取String响应
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            String responseBody = responseEntity.getBody();
            
            if (responseBody != null) {
                // 使用ObjectMapper解析JSON
                Map<String, Object> response = objectMapper.readValue(responseBody, Map.class);
                
                if (response.containsKey("openid")) {
                    return response;
                } else {
                    // 如果获取失败，返回错误信息
                    Map<String, Object> errorResult = new HashMap<>();
                    errorResult.put("error", "获取openid失败");
                    errorResult.put("error_msg", response.get("errmsg"));
                    return errorResult;
                }
            } else {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("error", "获取openid失败");
                errorResult.put("error_msg", "响应为空");
                return errorResult;
            }
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("error", "调用微信API异常");
            errorResult.put("error_msg", e.getMessage());
            return errorResult;
        }
    }
    
    @Override
    public boolean isProfileComplete(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return false;
        }
        
        // 检查必要字段是否完整
        return user.getUsername() != null && !user.getUsername().trim().isEmpty() &&
               user.getClanId() != null &&
               user.getBranchId() != null;
    }
} 